package com.crm.controller;


import com.crm.pojo.Employee;
import com.crm.service.EmployeeService;
import com.crm.utils.R;
import com.crm.utils.jwt.JwtUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * 登陆接口
 */
@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    EmployeeService employeeService;

    R r = new R();

    @PostMapping("/login")
    public R login(String username, String password, HttpServletRequest request, HttpServletResponse response) {

        try {
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
            subject.login(usernamePasswordToken);

            Employee employee= employeeService.findByAccount(username);
//            request.getSession().setAttribute("user", byUsername);
            r.setCode(200);
            r.setMsg("登录成功！");
            r.setData(employee);
            //1.登录成功后，后端生成token令牌。
            String authorization = JwtUtils.createJwt(UUID.randomUUID().toString(), JwtUtils.JWT_SECERT, JSONObject.toJSONString(usernamePasswordToken), JwtUtils.TTMILLIS);
            //2.通过响应头返回给前端
            r.setToken(authorization);
            response.setHeader("Authorization", authorization);
        } catch (UnknownAccountException e) {
            System.out.println("==账户有误==");
            r.setCode(500);
            r.setMsg("账户或密码有误");
            r.setData(null);
        } catch (IncorrectCredentialsException e) {
            System.out.println("==密码有误==");
            r.setCode(500);
            r.setMsg("账户或密码有误");
            r.setData(null);
        } catch (LockedAccountException e) {
            System.out.println("==账号被锁==");
            r.setCode(500);
            r.setMsg("账号被锁");
            r.setData(null);
        } catch (AuthenticationException e) {
            System.out.println("==认证错误==");
            r.setCode(500);
            r.setMsg("认证错误");
            r.setData(null);
        }
        return r;
    }

    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    @ResponseBody
    public R logout() {//shiro退出
        R r = new R();
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        r.setCode(200);
        r.setMsg("退出登录");
        return r;
    }

}
